package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import physicalobject.Bar;
import physicalobject.Connector;
import physicalobject.FixedMass;
import physicalobject.Mass;
import physicalobject.Muscle;
import physicalobject.Spring;

/**
 * Converts a text file into a set of masses and springs.
 * @author Robert C. Duvall
 * Patrick Royal - par24
 * Michele Reshef - mr148
 */
public class Factory {
    /**
     * Creates a new scanner and loops through the file, line by line.
     * @param sim the canvas on which to draw the shapes
     * @param modelFile the data file
     */
    public void loadModel (Simulation sim, File modelFile) {
        try {
            Scanner input = new Scanner(modelFile);
            while (input.hasNext()) {
                Scanner line = new Scanner(input.nextLine());
                if (line.hasNext()) {
                    String type = line.next();
                    if ("mass".equals(type)) {
                        sim.add(massCommand(line));
                    }
                    else if ("spring".equals(type)) {
                        sim.add(springCommand(line, sim, type));
                    }
                    else if ("muscle".equals(type)) {
                        sim.add(muscleCommand(line, sim, type));
                    }
                }
            }
            input.close();
        }
        catch (FileNotFoundException e) {
            // should not happen because File came from user selection
            e.printStackTrace();
        }
    }

    private Connector muscleCommand (Scanner line, Simulation sim,
            String type) {
        int m1 = line.nextInt();
        int m2 = line.nextInt();
        double restLength = line.nextDouble();
        double amp = line.nextDouble();
        double ks = line.nextDouble();
        return new Muscle(sim.getMass(m1),
                sim.getMass(m2),
                restLength,
                ks,
                amp);
    }

    private Mass massCommand (Scanner line) {
        int id = line.nextInt();
        double x = line.nextDouble();
        double y = line.nextDouble();
        double mass = line.nextDouble();
        if (mass < 0) {
            return new FixedMass(id, x, y);
        }
        return new Mass(id, x, y, mass);
    }

    private Connector springCommand (Scanner line, Simulation sim,
            String type) {
        int m1 = line.nextInt();
        int m2 = line.nextInt();
        double restLength = line.nextDouble();
        double ks = line.nextDouble();
        if (ks < 0) {
            return new Bar(sim.getMass(m1),
                    sim.getMass(m2),
                    restLength,
                    ks);
        }
        return new Spring(sim.getMass(m1),
                sim.getMass(m2),
                restLength,
                ks);
    }
}
